package com.esiran.payadmin.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XMLUtil {
    public static Map<String,String> toMap(String xmlText){
        try {
            Map<String,String> map = new HashMap<String, String>();
            Document doc = DocumentHelper.parseText(xmlText);
            Element root = doc.getRootElement();
            for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
                Element e = (Element) iterator.next();
                map.put(e.getName(), e.getText());
            }
            return map;
        } catch (DocumentException e) {
            return null;
        }
    }
    public static String toXml(Map<String,String> map){
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");

        Element author1 = root.addElement("author")
                .addAttribute("name", "James")
                .addAttribute("location", "UK")
                .addText("James Strachan");

        Element author2 = root.addElement("author")
                .addAttribute("name", "Bob")
                .addAttribute("location", "US")
                .addText("Bob McWhirter");

        return document.getStringValue();

    }
}
